package org.zattix.servlet;

import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.zattix.bean.Category;
import org.zattix.bean.Discussion;
import org.zattix.ejb.CategoryFacade;
import org.zattix.ejb.DiscussionFacade;
import org.zattix.ejb.UserFacade;

/**
 *
 * @author s.rainoldi
 */
@WebServlet(name = "ServletCategory", urlPatterns = {"/category"})
public class ServletCategory extends HttpServlet {
    @EJB
    private UserFacade userFacade;
    @EJB
    private DiscussionFacade discussionFacade;
    @EJB
    private CategoryFacade categoryFacade;
    

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        // Arriva col nome?
        if (name != null) {
            Category category = categoryFacade.getCategoryByTitleUrl(name);
            category.getDiscussions();
            if (category != null) {
                // Ha fatto un post?
                if (request.getMethod().equals("POST")) {
                    String text = request.getParameter("text");
                    Discussion discussion = new Discussion();
                    discussion.setCategory(category);
                    discussion.setTitle(text);
                    discussionFacade.create(discussion);
                    category.getDiscussions().add(discussion);
                    categoryFacade.edit(category);
                }
                request.setAttribute("title", category.getTitle());
                request.setAttribute("selectedCategory", category);
                request.setAttribute("category", category);
                request.getRequestDispatcher("/WEB-INF/pages/category.jsp").forward(request, response);

            }

        } // Mostra la lista
        else {
            request.getRequestDispatcher("/WEB-INF/pages/categories.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Categories servlet";
    }// </editor-fold>
}
